package com.ajaxw.dbkit;

import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;

import com.mysql.jdbc.Connection;
import com.mysql.jdbc.Statement;

public class DBAccess {

	// private String defURL =
	// "jdbc:mysql://localhost:3306/indexer?characterEncoding=gbk";
	private String defURL = "jdbc:mysql://localhost:3306/indexer?characterEncoding=utf8";
	private Connection con = null;

	{
		Class.forName("com.mysql.jdbc.Driver");
	}

	public DBAccess() throws ClassNotFoundException, SQLException {
		con = (Connection) DriverManager
				.getConnection(defURL, "root", "123456");
	}

	public DBAccess(String url) throws ClassNotFoundException, SQLException {
		con = (Connection) DriverManager.getConnection(url, "root", "123456");
	}

	public DBAccess(String url, String userName, String password)
			throws ClassNotFoundException, SQLException {
		con = (Connection) DriverManager.getConnection(url, userName, password);
	}

	protected void finalize() {
		try {
			if (con != null && !con.isClosed())
				con.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	public ResultSet executeQuery(String query) throws SQLException {
		// con.setEncoding("gbk");
		Statement stmt = (Statement) con.createStatement();
		return stmt.executeQuery(query);
	}

	public boolean execute(String sql) throws SQLException {
		// con.setEncoding("gbk");
		Statement stmt = (Statement) con.createStatement();
		return stmt.execute(sql);
	}

	public void setEncoding(String encoding) {
		con.setEncoding(encoding);
	}

}
